﻿using System;
using System.Web;
using System.Collections;
using System.Linq;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using System.Collections.Generic;
using System.Diagnostics;
using mojoPortal.Web.Framework;
using blackhouse.BlackApart.Web;

namespace blackhouse.Aparts.Web.Handlers {
	public class ResolveLanguageSite : IHttpModule {
		/// <summary>
		/// You will need to configure this module in the web.config file of your
		/// web and register it with IIS before being able to use it. For more information
		/// see the following link: http://go.microsoft.com/?linkid=8101007
		/// </summary>
		#region IHttpModule Members

		public void Dispose() {
			//clean-up code here.
		}

		public void Init(HttpApplication context) {
			context.BeginRequest += new EventHandler(context_BeginRequest);

		}

		void context_BeginRequest(object sender, EventArgs e) {
			this.BeginRequest(sender);

		}

		private void BeginRequest(object sender) {
			if (sender == null) return;

			HttpApplication app = (HttpApplication)sender;

			string requestPath = app.Request.Path;

			if (WebUtils.IsRequestForStaticFile(requestPath)) return;

			if (requestPath.ContainsCaseInsensitive("Update.aspx")) return;
			if (requestPath.ContainsCaseInsensitive(".ashx")) return;

			if (!this.IsDesignedForThisRequest(app.Request.RawUrl)) return;

			this.SetInstance();
			this.RedirectIfFolderNotSet();




			//if (this.IsDirectDomain()) {
			//    if (!this.PrevSettedLangCookie())
			//        this.SetCookieFromUserLanguage();

			//    this.RedirectToLangCookie();
			//}
			//this.EnsureIsSetRightCookie();
		}

		private void EnsureIsSetRightCookie() {
			Debug.Write(languageCookie == null ? "NULL" : languageCookie.Value);
			if (this.languageCookie != null) {
				if (this.siteFolders.Any(s => s == this.languageCookie.Value))
					return;
				else
					this.AddCurrentSiteFolderNameToResponseCookie();
			}
			else
				this.AddCurrentSiteFolderNameToResponseCookie();
		}

		private bool IsDesignedForThisRequest(string rawUrl) {
			string[] parts = rawUrl.Split('.');
			string lastPart = parts[parts.Length - 1];
			if (lastPart.Length == 3) return false;
			if (lastPart == "js") return false;
			if (rawUrl.Contains("Update.aspx")) return false;
			return true;
		}

		private void AddCurrentSiteFolderNameToResponseCookie() {
			this.languageCookie = new HttpCookie("language", this.siteFolders[0]);
			context.Response.Cookies.Add(this.languageCookie);
		}

		private void RedirectToLangCookie() {
			if (languageCookie != null) {
				string url = "/" + languageCookie.Value;
				HttpContext.Current.Response.Redirect(url);
			}
		}

		private void SetCookieFromUserLanguage() {
			string[] languages = HttpContext.Current.Request.UserLanguages;
			for (int xl = 0; xl < languages.Length; xl++) {
				string language = languages[xl].Split(';')[0];
				if (SiteFolder.Exists(language)) {
					this.languageCookie = new HttpCookie("language", language);
					context.Response.Cookies.Add(this.languageCookie);
					break;
				}
			}
			if (this.languageCookie == null)
				this.languageCookie = new HttpCookie("language", this.siteFolders[0]);
		}

		private bool PrevSettedLangCookie() {
			if (this.languageCookie == null) return false;
			return SiteFolder.Exists(this.languageCookie.Value);
		}

		private bool IsDirectDomain() {
			return this.rawUrl == "/";
		}

		private HttpContext context;
		private string rawUrl;
		private HttpCookie languageCookie;
		private string[] siteFolders = new string[0];

		private void RedirectIfFolderNotSet() {
			SiteSettings ss = CacheHelper.GetCurrentSiteSettings();
			if (ss == null || ss.SiteId != 1) return;

			string currentFolder = this.VirtualFolderName();
			//if (string.IsNullOrEmpty(ss.SiteFolderName)) {
			//    // brak ustawionego folderu i cache, trzeba "poprawić" dane w cache
			//    if (string.IsNullOrEmpty(currentFolder)) {
			//        SiteFolder folder = SiteFolder.GetBySite(ss.SiteGuid).FirstOrDefault(sf => !string.IsNullOrEmpty(sf.FolderName));
			//        if (folder != null) {
			//            ss.SiteFolderName = folder.FolderName;
			//            context.Cache["SiteSettings_1"] = ss;
			//            context.Items["SiteSettings"] = ss;
			//        }
			//    }
			//}
			if (currentFolder != ss.SiteFolderName) {
				// trzeba zrobić 301
				string urlToRedirect = UrlUtils.LocalizeUrl(ss.SiteFolderName, context.Request.RawUrl.ReplaceEx(currentFolder, "").ReplaceEx("//", "/"));
				context.Response.RedirectPermanent(urlToRedirect, true);
			}
		}

		public string VirtualFolderName() {
			if (HttpContext.Current == null) return String.Empty;

			string folderName = HttpContext.Current.Items["PsyVirtualFolderName"] as string;

			if (folderName == null) {
				folderName = GetVirtualFolderName();
				if (folderName != null)
					HttpContext.Current.Items["PsyVirtualFolderName"] = folderName;
			}
			return folderName;


		}

		private string GetVirtualFolderName() {
			if (HttpContext.Current == null) return String.Empty;

			// find first level folder name
			// after site root
			string folderName = string.Empty;

			string requestPath =
				HttpContext.Current.Request.RawUrl.Replace("https://", string.Empty).Replace("http://", string.Empty);

			if (requestPath == "/") return folderName;

			if (
				(requestPath.IndexOf("/") > -1)
				&& (requestPath.LastIndexOf("/") > requestPath.IndexOf("/"))
				) {
				requestPath = requestPath.Substring(requestPath.IndexOf("/") + 1, requestPath.Length - 1);

				if (requestPath.IndexOf("/") > -1) {
					folderName = requestPath.Substring(0, requestPath.IndexOf("/"));

				}
			}

			if (folderName.Length != 2) // nazwy folderów - języków są dwu znakowe
				folderName = "";

			return folderName;
		}

		private void SetInstance() {
			this.context = HttpContext.Current;
			this.rawUrl = context.Request.RawUrl;
			this.languageCookie = context.Request.Cookies["language"];

			List<SiteFolder> folders = SiteFolder.GetBySite(CacheHelper.GetCurrentSiteSettings().SiteGuid);
			this.siteFolders = new string[folders.Count];
			for (int xf = 0; xf < folders.Count; xf++) {
				this.siteFolders[xf] = folders[xf].FolderName;
			}

			if (this.siteFolders.Length == 0)
				this.siteFolders = new string[] { "" };
		}

		internal static string FormatAddressByLanguage(string url) {
			List<SiteFolder> folders = SiteFolder.GetBySite(CacheHelper.GetCurrentSiteSettings().SiteGuid);
			if (folders.Count > 0)
				return "/" + folders[0].FolderName + url;
			else return url;
		}

		#endregion

	}
}
